package com.laixu.estore.service;

import com.laixu.estore.bean.dto.UserLoginDTO;
import com.laixu.estore.bean.dto.UserRegisterDTO;
import com.laixu.estore.bean.pojo.User;
import com.laixu.estore.bean.vo.UserInfo;
import com.laixu.estore.bean.vo.UserLoginVo;
import com.laixu.estore.dao.UserDao;
import com.laixu.estore.util.BeanCopyUtils;
import com.laixu.estore.util.JsonWebTokenUtils;
import com.laixu.estore.web.exception.BookStoreException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
@Slf4j
public class UserService {
    private final UserDao userDao;

    public UserLoginVo login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        // 1.校验用户密码
        User user = userDao.login(username,password);
        if(user == null){ // 账号密码匹配不上
            throw new BookStoreException(BookStoreException.CodeMsgEnum.USER_USERNAME_OR_PASSWORD_ERROR);
        }
        // 2.查询用户信息
        UserInfo userInfo = BeanCopyUtils.copyBean(user, UserInfo.class);
        // 3.产生jwt username | id
        String jwt = JsonWebTokenUtils.createJWT(String.valueOf(user.getId()));
        // 4.返回响应值
        UserLoginVo userLoginVo = new UserLoginVo(jwt, userInfo);
        log.info("登录返回数据：{}",userLoginVo);
        return userLoginVo;
    }

    public UserInfo getUserById(int id) {
        User user = userDao.getUserById(id);
        UserInfo userInfo = BeanCopyUtils.copyBean(user, UserInfo.class);
        return userInfo;
    }

    //注册
    public void register(UserRegisterDTO userRegisterDTO) {
        User user = new User();
        user.setUsername(userRegisterDTO.getUsername());
        user.setPassword(userRegisterDTO.getPassword());
        user.setPhone(userRegisterDTO.getPhone());
        user.setAvatar(userRegisterDTO.getAvatar());
        System.out.println("userRegisterDTO.getAvatar() = " + userRegisterDTO.getAvatar());
        user.setGender(userRegisterDTO.getGender());
        user.setBirthday(userRegisterDTO.getBirthday());
        userDao.insertUser(user);
    }
}